import createG2 from 'g2-react';
import { Stat } from 'g2';
import G2 from 'g2';     //G2要引入，坑死了，大爷的
import React from 'react';
import ReactDOM from 'react-dom';
import { DatePicker,Modal} from 'antd';
import moment from 'moment';
import ajax from '../../../../utils/ajax';
import Logger from '../../../../utils/Logger';

const logger = Logger.getLogger('Test');

const Chart = createG2(chart => {
      const Stat = G2.Stat;
      const colorMap = {
        'totalCount': '#7EC856',
        'validCount': '#38B8F2'
      }

      chart.axis('count', {//设置x轴别名离轴的距离
        titleOffset: 55,
      });
      chart.col('count', {//设置纵坐标之间的间隔
         tickInterval: 30,
         alias:'预约人数',
      });

      chart.axis('simpleDayStr', {//设置y轴别名离轴的距离
          titleOffset: 55
      });
      chart.col('simpleDayStr', {//为y轴设置别名
          alias:'时间',
      });

      chart.legend(false);//关闭图例

    //   chart.axis('count', {
    //     formatter: function(val) {
    //       return (val / 10) ;
    //     }
    //   });


      chart.interval(['dodge', 'stack']).position('simpleDayStr*count').color('type*number', function(type, number) {
        return colorMap[number];
      }).size(10);

      chart.render();
});

const { MonthPicker, RangePicker } = DatePicker;
const confirm = Modal.confirm;
const thirtyDays=30*24*60*60*1000;//定义一个30天常量
const day='';
const startDay='';
const stopDay='';

const Frame = G2.Frame;
let frame;

/**
 * 开始时间不能大于现在时间
 */
function disabledDate(current) {
  return current && current.valueOf() > Date.now();
}

function showdate(n){//得到日期前29天日期
  var date = new Date(new Date()-0+n*86400000);
  var result=""+date.getFullYear();
  var month=date.getMonth()+1;
  var day=date.getDate();
  if((month)<10){
     result=result+"0"+(month);
  }else{
    result=result+""+(month);
  }
  if(date.getDate()<10){
     result=result+"0"+ day;
  }else{
    result=result+""+ day;
  }
  return result;
} 

/**
 * 分组层叠柱状图组件
 */
class Test extends React.Component {

  constructor(props) {
    super(props);
    this.initData(startDay,stopDay);
  }

  state={
    open:false,//控制日期控件开闭
    visible: false,//控制警告控件开闭
    width: 500,
    height: 800,
    plotCfg: {
        margin: [50, 100,90, 120],
    },
    forceFit: true,
    frameData:[],
  }

  initData(startDay,stopDay){
    var self = this;
    const paramData={};
    if(startDay&&stopDay){
      paramData.startDay=startDay;
      paramData.stopDay=stopDay;
    }else{
      paramData.startDay=showdate(-29);
      paramData.stopDay=new Date().format('yyyyMMdd');
    }
    const url = '/statistic/getMuseumAllAppointmentInfoByStartDayAndStopDay';
    ajax.post({
       url: url,
       params:paramData,
       async:false,
       success: function (res) {
          var tmpData=[];
          for(var i=0;i<res.data.data.length;i++){
              tmpData.push(res.data.data[i]);
          }
          frame=new Frame(tmpData);
          frame = Frame.combinColumns(frame,['totalCount','validCount'],'count', 'number', 'simpleDayStr','day');
          frame.addCol('type', function(obj) {
               var key = obj.number;
               var type;
               if (key === 'totalCount'||key === 'validCount') {
                    type = '数量';
               }
               return type;
          });
       }
     })
  }

    /**
   * 时间改变发生事件
   */
  onEndChange = (value) =>{
     var day=new Date(value).format('yyyyMMdd');
     if(day){//day必须有值才可以
        this.initUserData(day);//重新处理请求
     }
  }

  /**
   * 判断时间间隔不能超过30天
   */
  onRangeTime=(value)=>{
      //得到开始时间和结束时间
      var startDay=new Date(value[0]);
      var stopDay=new Date(value[1]);
      var tmpDate=stopDay-startDay;
      if(tmpDate>thirtyDays){
         this.setState({open: true});//日期对话框不能关闭
         this.showConfirm();
      }else{
        startDay=startDay.format('yyyyMMdd');
        stopDay=stopDay.format('yyyyMMdd');
        this.setState({open: false});
        this.initData(startDay,stopDay);
      }
  }

  /**
  * 定义警告对话框
  */
  showConfirm() {
     var _this=this;
     confirm({
        title: '警告',
        content: '最多选择30天日期，请重新选择！',
        onOk() {
           _this.setState({open: true});//警告对话框，点击确认时不能把时间对话框关闭
        },
        onCancel() {
            _this.setState({open: true});//警告对话框，点击取消时时不能把时间对话框关闭
         },
     });
  }

 render() {
    return (
        <div>
            <div >
                <span>选择日期：
                    <RangePicker 
                       disabledDate={disabledDate} 
                       format="YYYY-MM-DD HH:mm:ss" size={'Large'}
                       onChange={this.onRangeTime}
                       open={this.state.open}
                    />
               </span>
            </div>
            <Chart 
            data={frame}
            width={this.state.width}
            height={this.state.height}
            plotCfg={this.state.plotCfg}
            forceFit={this.state.forceFit}
           />
         </div>
    );
  }
}

export default Test;